package com.jinunn.yygh.listener;

import com.alibaba.excel.context.AnalysisContext;
import com.alibaba.excel.event.AnalysisEventListener;
import com.alibaba.fastjson.JSON;
import com.atguigu.yygh.model.cmn.Dict;
import com.atguigu.yygh.vo.cmn.DictEeVo;
import com.jinunn.yygh.mapper.DictMapper;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.BeanUtils;
import org.springframework.transaction.annotation.Transactional;
import org.springframework.util.StringUtils;

import java.util.ArrayList;
import java.util.List;

/**
 * @author : JinDun
 * @date : 2021/4/25 22:48
 */
@Slf4j
public class DictListener extends AnalysisEventListener<DictEeVo> {

    private final DictMapper dictMapper;

    public DictListener(DictMapper dictMapper) {
        this.dictMapper = dictMapper;
    }

    List<DictEeVo> dictVoList = new ArrayList<>();

    @Override
    public void invoke(DictEeVo dictEeVo, AnalysisContext analysisContext) {
        log.info("解析到一条数据:{}", JSON.toJSONString(dictEeVo));
        if (StringUtils.isEmpty(dictEeVo.getName())){
            throw new RuntimeException("请按照模板规范将表格补充完整");
        }
        dictVoList.add(dictEeVo);
    }

    @Override
    @Transactional(rollbackFor = Exception.class)
    public void doAfterAllAnalysed(AnalysisContext analysisContext) {
        log.info("进入到：doAfterAllAnalysed  方法中");
        dictVoList.forEach(dictEeVo -> {
            Dict dict = new Dict();
            BeanUtils.copyProperties(dictEeVo,dict);
            dictMapper.insert(dict);
        });
        log.info("存储数据库成功！！");
    }
}
